//
//  ZTFileHandle.m
//  ZHYYTool
//
//  Created by MT-SW-005 on 2021/9/17.
//  Copyright © 2021 MT-SW-005. All rights reserved.
//

#import "ZTFileHandle.h"

@implementation ZTFileHandle

/**
* 根据路径判断文件/文件夹是否存在
*
@param filePath 文件夹路径
@return BOOL   YES or NO
*/
+(BOOL)isExistFile:(NSString*)filePath
{
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        return YES;
    } else{
        return NO;
    }
}


/**
* 删除文件
*
@param filePath 文件夹路径
@return BOOL   YES or NO
*/
+(BOOL)removeFile:(NSString*)filePath
{
    NSError *err = nil;
    if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
        [[NSFileManager defaultManager] removeItemAtPath:filePath error:&err];
        if (err != nil) {
            NSLog(@"Delete File: %@ Failed",filePath);
            return NO;
        } else {
             NSLog(@"Delete File: %@  Success",filePath);
            return YES;
        }
    } else {
        NSLog(@"File: %@  Dont Exist",filePath);
        return NO;
    }
}



// /vault/logPAthName/2021_11_02/DUT1/sn_17_14_56
+(NSString*)createFileForDUT:(int)slot FilePath:(NSString*)filePath SN:(NSString*)sn
{
    NSError *err;
    NSString *hostDir = [NSString stringWithFormat:@"%@/DUT%d",filePath,slot];
     //创建文件夹
     if(![[NSFileManager defaultManager] fileExistsAtPath:hostDir]){
         [[NSFileManager defaultManager] createDirectoryAtPath:hostDir withIntermediateDirectories:YES attributes:nil error:&err];
     }
     
    //获取格式化日期
    NSDateFormatter *format = [[NSDateFormatter alloc] init];
//    [format setDateFormat:@"MM_dd_HH_mm_ss"];
    [format setDateFormat:@"HH_mm_ss"];
    NSString *ts = @"";
    ts = [format stringFromDate:[NSDate date]];
    
    NSString *dir = [NSString stringWithFormat:@"%@/%@_%@",hostDir,sn,ts];
    if ([[NSFileManager defaultManager] fileExistsAtPath:hostDir]) {
        NSLog(@"hostIDr: %@",hostDir);
        if(![[NSFileManager defaultManager] fileExistsAtPath:dir]){
            [[NSFileManager defaultManager] createDirectoryAtPath:dir withIntermediateDirectories:YES attributes:nil error:&err];
            NSLog(@"create Directory: %@",dir);
        }
    }
    return dir;
}

    

+(NSString*)createFileWithPath:(NSString*)path FileName:(NSString*)fileName
{
    BOOL isExistedPath = [self isExistFile:path];
    if (isExistedPath == NO) {
        [self createDirectory:path];
    }
    NSString *filePath = [NSString stringWithFormat:@"%@/%@",path,fileName];
    BOOL isExistedFile = [self isExistFile:filePath];
    
    if (isExistedFile) {
        return filePath;
    } else {
        [[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];
        return filePath;
    }
}


+(NSString*)createFile:(NSString*)fileName
{
    BOOL isExistedFile = [self isExistFile:fileName];
    if (isExistedFile) {
        return fileName;
    } else {
        [[NSFileManager defaultManager] createFileAtPath:fileName contents:nil attributes:nil];
        return fileName;
    }
}


+(NSString*)createDirectory:(NSString*)path
{
    NSError *err;
    NSString *filePath = [NSString stringWithFormat:@"%@",path];
    BOOL isExistedFile = [self isExistFile:filePath];
    if (isExistedFile) {
        return filePath;
    } else {
         [[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:&err];
     }
    return filePath;
    
    
}


/*
 *加载plist文件
 */
+ (id)readPlistFile:(NSString *)filePath
 {
     id plistData = nil;
     if ([self isExistFile:filePath]) {
         plistData = [NSDictionary dictionaryWithContentsOfFile:filePath];
         if (plistData == nil) {
             plistData = [[NSArray alloc] initWithContentsOfFile:filePath];
         }
     }
     else{
         NSLog(@"file not exist");
     }
     return plistData;
 }



/*
*加载json文件
*/
+ (id)readJsonFile:(NSString *)filePath
{
    id jsonData = nil;
    NSError *error;
    if ([self isExistFile:filePath]) {
        jsonData = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:filePath] options:0 error:&error];
        if (error) {
            NSLog(@"%@", error.localizedDescription);
        }
    }else {
         NSLog(@"file not exist");
    }
    return jsonData;
    
}




/*
 *追加的方式写入字符串数据到文件
 */
+(void)writeString:(NSString*)str toFilePAth:(NSString *)path
{
    NSString *writeStr = [NSString stringWithFormat:@"%@\n",str];
    if (![[NSFileManager defaultManager] fileExistsAtPath:path])
    {
        [[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil];
    }
    
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForUpdatingAtPath:path];
    [fileHandle seekToEndOfFile];
    [fileHandle writeData:[writeStr dataUsingEncoding:NSUTF8StringEncoding]];//NSString -->NSData,写入NSData数据
    [fileHandle closeFile];
}


/**
* 从文件中读取数据
*
@param file 读取的文件
@return 返回读取的数据
*/
+(NSData*)readDataFromFile:(NSString*)file
{
    NSData *readData = [NSData data];
    if ([self isExistFile:file]) {
        NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:file];
        readData = [fileHandle readDataToEndOfFile];
        [fileHandle closeFile];
        NSLog(@"Read File: %@  Success",file);
    }else{
        NSLog(@"File: %@  Dont Exist",file);
    }
    return readData;
}



/**
* 获取文件数据长度
*
@param file 读取的文件
@return 返回读取的数据长度
*/
+(NSUInteger)fileDataLength:(NSString*)file
{
    NSUInteger length = 0;
    if ([self isExistFile:file]) {
        NSFileHandle *fileHandle = [NSFileHandle fileHandleForReadingAtPath:file];
        length = [[fileHandle availableData] length]; //获取数据长度
        [fileHandle closeFile];
        NSLog(@"File: %@  Length:%ld",file,length);
    } else {
        NSLog(@"File: %@  Dont Exist",file);
    }
    return length;
}





+(void)writeStringLog:(NSString*)str toLogFile:(NSString*)logFile
{
    [self writeString:str toFilePAth:logFile];
}


+(void)writeCSVHeader:(NSString*)header toCSVFile:(NSString*)CSVFile
{
    [self writeString:header toFilePAth:CSVFile];
}

+(void)writeCSVItem:(NSString*)csvItem toCSVFile:(NSString*)CSVFile
{
    [self writeString:csvItem toFilePAth:CSVFile];
}


+(void)saveAndPrintLog:(NSString*)logStr LogFile:(NSString*)logfile
{
    [self writeStringLog:logStr toLogFile:logfile];
    NSLog(@"%@",logStr);
}


/*
*将NSlog打印信息保存到指定目录下的文件中
*/
+ (void)redirectNSlogToFolder:(NSString*)path logName:(NSString*)name
{
    NSString *logFilePath = path;
    NSFileManager *fileManager = [NSFileManager defaultManager];
    BOOL fileExists = [fileManager fileExistsAtPath:logFilePath];
    if (!fileExists) {
        [fileManager createDirectoryAtPath:logFilePath  withIntermediateDirectories:YES attributes:nil error:nil];
    }
    NSLog(@"log path:%@",logFilePath);
    NSString *logFile = [NSString stringWithFormat:@"%@/%@.log",logFilePath,name];
    if (![fileManager fileExistsAtPath:logFile]) {
        [fileManager createFileAtPath:logFile contents:nil attributes:nil];
        NSLog(@"create:%@",logFile);
    }
    // 将log输入到文件
    freopen([logFile cStringUsingEncoding:NSASCIIStringEncoding], "a+", stdout);
    freopen([logFile cStringUsingEncoding:NSASCIIStringEncoding], "a+", stderr);
}

@end

